package com.lninl.controller;

import com.lninl.model.Uri;
import com.lninl.repository.UriRepository;
import com.lninl.service.UriService;
import com.lninl.util.Spider;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Controller
public class UriController {

    @Autowired
    private UriService service;

    @Autowired
    UriRepository repository;

    /**
     * 根据名字返回链接信息，如果不存在则创建之后再返回。
     *
     * @param uriForm
     * @return
     */
    @RequestMapping(value = "/uri/url", method = RequestMethod.POST)
    @ResponseBody
    public Uri getByUrl(@ModelAttribute Uri uriForm) {

        String url = uriForm.getUrl();
        if (url == null) {
            return null;
        }
        // TODO 网址验证

        Uri entity = repository.findByUrl(url);
        if (entity == null) {
            Spider spider = new Spider(url);//爬取网页内容

            entity = new Uri();
            entity.setUrl(url);
            entity.setTitle(spider.getTitle());
            entity.setDescription(spider.getDescription());
            entity.setCreated(new DateTime());
            entity.setStatus(Uri.NORMAL);
            return repository.save(entity);
        }

        return entity;
    }

    /**
     * 显示添加表单
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/uri/add")
    public String addForm(Model model) {
        model.addAttribute(new Uri());
        return "/uri/add";
    }

    /**
     * 添加链接
     *
     * @param uri
     * @param bindingResult
     * @param model
     * @return
     */
    @RequestMapping(value = "/uri", method = RequestMethod.POST)
    public ResponseEntity add(@Valid Uri uri, BindingResult bindingResult,
                              Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute(uri);
            return new ResponseEntity<>("{"
                    + bindingResult.getFieldError().getField() + ":"
                    + bindingResult.getFieldError().getCode() + "}",
                    HttpStatus.OK);
        }
        uri.setCreated(new DateTime());
        uri.setStatus(1);
        return new ResponseEntity<>(repository.save(uri), HttpStatus.OK);
    }

    /**
     * 得到链接
     *
     * @param uri
     * @param model
     * @return
     */
    @RequestMapping(value = "/uri/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Uri get(@PathVariable("id") Uri uri, Model model) {
        return uri;
    }

    /**
     * 获取链接列表
     */
    @RequestMapping(value = "/uri", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Page<Uri> uris(Pageable pageable) {
        return repository.findAll(pageable);
    }

    @RequestMapping(value = "/uri/{id}/edit", method = RequestMethod.GET)
    public String updateForm(@PathVariable("id") Uri uri, Model model) {
        model.addAttribute(uri);
        return "/uri/edit";
    }

    /**
     * 更新链接
     *
     * @param oldUri
     * @param uri
     * @param bindingResult
     * @param model
     * @return
     */
    @RequestMapping(value = "/uri/{id}", method = RequestMethod.PUT)
    public String update(@PathVariable("id") Uri oldUri, @Valid Uri uri,
                         BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            model.addAttribute(uri);
            return "/uri/add";
        }

        // TODO
        repository.save(oldUri);
        return "redirect:/uri";
    }

    /**
     * 删除链接
     *
     * @param id
     * @param model
     * @return
     */
    @RequestMapping(value = "/uri/{id}", method = RequestMethod.DELETE)
    public String delete(@PathVariable Long id, Model model) {
        repository.delete(id);
        return "redirect:/uri";
    }

}
